package com.tingyuge.thinking.spring.dependency.source;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.io.ResourceLoader;

import javax.annotation.PostConstruct;

/**
 * 基于注解 依赖字段 注入
 *
 * @author xiaodao
 * @version 1.0
 * @date 2021/6/29
 */
public class DependencySourceDemo {

    //这个注入早于 postBeanProperties 也早于 Setter --->@PostConstructor
    @Autowired
    private BeanFactory beanFactory;
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    private ApplicationContext applicationContext;


    @PostConstruct
    public void init() {
        System.out.println("beanFactory == applicationContext " + (beanFactory == applicationContext));
        System.out.println("beanFactory == applicationContext.getBeanFactory() " + (beanFactory == applicationContext.getAutowireCapableBeanFactory()));
        System.out.println("beanFactory == applicationContext " + (resourceLoader == applicationContext));
        System.out.println("beanFactory == applicationContext " + (applicationEventPublisher == applicationContext));

    }

    @PostConstruct
    public void initByLookup() {
        getBean(BeanFactory.class);
        getBean(ResourceLoader.class);
        getBean(ApplicationEventPublisher.class);
        getBean(ApplicationContext.class);

    }

    private <T> T getBean(Class<T> bean) {
        try {
            return beanFactory.getBean(bean);
        } catch (NoSuchBeanDefinitionException e) {
            System.out.println("当前类型:" + bean.getName() + " 无法在beanFactory中查找");
        }
        return null;

    }


    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //注册 configuration class（配置类）--->也是 spring bean
        applicationContext.register(DependencySourceDemo.class);
        //启动应用上下文
        applicationContext.refresh();
        //依赖查找  AnnotationDependencyFieldInjectionDemo
        DependencySourceDemo demo = applicationContext.getBean(DependencySourceDemo.class);


        //显示关闭应用上下文
        applicationContext.close();
    }
}
